package com.tjbklx1.redis.me;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisHash {

	/**
	 * 设置Map值
	 * 
	 * @param key
	 * @param value
	 */
	public static void hset(String key, String field, String value) {
		if (StringUtils.isEmpty(value) || StringUtils.isEmpty(value) || StringUtils.isEmpty(field)) {
			return;
		}
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisConnection.getPool();
			jedis = pool.getResource();
			jedis.hset(key, field, value);
		} catch (Exception e) {
			// 释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			// 返还到连接池
			RedisConnection.returnResource(pool, jedis);
		}
	}

	/**
	 * 从Map中获取value
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public static String hget(String key, String field) {
		String value = null;
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
			return value;
		}
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisConnection.getPool();
			jedis = pool.getResource();
			value = jedis.hget(key, field);
		} catch (Exception e) {
			// 释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			// 返还到连接池
			RedisConnection.returnResource(pool, jedis);
		}
		return value;
	}

	/**
	 * 获取Map值
	 * 
	 * @param key
	 * @param value
	 */
	@SuppressWarnings("rawtypes")
	public static Map hgetAll(String key) {
		if (StringUtils.isEmpty(key)) {
			return null;
		}
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisConnection.getPool();
			jedis = pool.getResource();
			Map map = jedis.hgetAll(key);
			return map;
		} catch (Exception e) {
			// 释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			// 返还到连接池
			RedisConnection.returnResource(pool, jedis);
		}
		return null;
	}
	
	
}
